<template>
  <div class="app-container">
    <el-card>
      <!-- 雷达图标题 -->
      <div slot="header" class="clearfix">
        <span>学生能力雷达图对比分析</span>
      </div>

      <!-- 选择器 -->
      <div class="selector-container">
        <el-autocomplete
          v-model="majorIdLabel"
          :fetch-suggestions="queryMajor"
          placeholder="请输入专业ID"
          @select="handleMajorSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>

        <el-autocomplete
          v-model="classIdLabel"
          :fetch-suggestions="queryClass"
          placeholder="请输入班级ID"
          @select="handleClassSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>

        <el-autocomplete v-model="studentId" :fetch-suggestions="queryStudent" placeholder="请输入学号" @select="handleStudentSelect">
          <template #default="{ item }"><div class="autocomplete-item">{{ item.label }}</div></template>
        </el-autocomplete>

        <el-button type="primary" @click="fetchData">查询</el-button>
      </div>

      <!-- 雷达图展示 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else class="radar-chart-container">
        <div ref="radarChart" class="chart" />
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getStudentAbility,
  getClassAbility,
  getMajorAbility
} from '@/api/teacher'

export default {
  name: 'StudentAbilityCompare',
  data() {
    return {
      // 映射表（自动生成）
      majorMapping: {}, // 中文专业名 => 数据库ID
      classMapping: {}, // 专业ID => 班级列表
      studentMapping: {}, // 班级ID => 学生列表

      // 输入绑定字段
      majorIdLabel: '', // 展示用中文名
      majorIdValue: '', // 接口用英文ID
      classIdLabel: '', // 展示用班级名
      classIdValue: '', // 接口用英文ID
      studentId: '', // 学号

      // 自动补全选项
      majorOptions: [],
      classOptions: [],
      studentOptions: [],

      // 能力数据
      radarData: {
        student: null,
        class: null,
        major: null
      },

      loading: false
    }
  },
  created() {
    // 模拟原始数据输入（可以从接口获取）
    const rawMajorData = `
major1,college1,计科
major2,college1,AI
major3,college1,大数据
major4,college1,物联
major5,college1,通信
major6,college1,电子
major7,college1,计算机类
major8,college1,曙光
major9,college1,电信类
major10,college1,建筑类
    `.trim().split('\n')

    const rawClassData = `
class126,major1,计科2401班
class104,major1,计科2402班
class41,major1,计科2403班
class111,major1,计科2404班
class86,major2,AI2401班
class121,major2,AI2402班
    `.trim().split('\n')

    const rawStudentData = `

    `.trim().split('\n')

    // 自动生成映射表
    this.generateMappings(rawMajorData, rawClassData, rawStudentData)
  },
  methods: {
    // 自动生成映射表
    generateMappings(majors, classes, students) {
      // 1️⃣ 解析专业映射
      majors.forEach(line => {
        // eslint-disable-next-line no-unused-vars
        const [id, _, label] = line.split(',')
        this.$set(this.majorMapping, label.trim(), id.trim())
        this.majorOptions.push({ label: label.trim(), value: id.trim() })
      })

      // 2️⃣ 解析班级映射
      classes.forEach(line => {
        const [classId, majorId, className] = line.split(',')
        if (!this.classMapping[majorId]) {
          this.$set(this.classMapping, majorId, [])
        }
        this.classMapping[majorId].push(classId.trim())

        // 同时保存 classId -> className 用于前端显示
        if (!this.classDisplayNames) this.classDisplayNames = {}
        this.classDisplayNames[classId.trim()] = className.trim()
      })

      // 3️⃣ 解析学生映射
      students.forEach(line => {
        const [studentId, classId] = line.split(',')
        if (!this.studentMapping[classId]) {
          this.$set(this.studentMapping, classId, [])
        }
        this.studentMapping[classId].push(studentId.trim())
      })
    },

    // 专业输入搜索
    queryMajor(queryString, cb) {
      const results = this.majorOptions.filter(item =>
        item.label.includes(queryString) || item.value.includes(queryString)
      )
      cb(results)
    },

    // 班级输入搜索
    queryClass(queryString, cb) {
      const results = this.classOptions.filter(item =>
        item.label.includes(queryString) || item.value.includes(queryString)
      )
      cb(results)
    },

    // 学生输入搜索
    queryStudent(queryString, cb) {
      const results = this.studentOptions.filter(item =>
        item.label.includes(queryString) || item.value.includes(queryString)
      )
      cb(results)
    },
    // 专业选择回调
    handleMajorSelect(item) {
      this.majorIdLabel = item.label
      this.majorIdValue = item.value
      this.classIdLabel = ''
      this.classIdValue = ''
      this.studentId = ''
      // 清空当前雷达图数据
      this.radarData = {
        student: null,
        class: null,
        major: null
      }
      // 获取班级选项
      this.fetchClassOptions(this.majorIdValue)
      // 新增：自动加载专业能力
      this.fetchAndRenderMajorData()
    },
    // 根据专业获取班级列表
    fetchClassOptions(majorId) {
      const classes = this.classMapping[majorId] || []
      this.classOptions = classes.map(id => ({
        label: this.classDisplayNames?.[id] || `${id}班`,
        value: id
      }))
    },
    // 查询并渲染专业能力雷达图
    async fetchAndRenderMajorData() {
      try {
        const res = await getMajorAbility(this.majorIdValue)
        if (res.success) {
          this.radarData.major = res.data
          this.renderChart()
        }
      } catch (error) {
        console.error('专业能力加载失败:', error)
      }
    },
    // 班级选择回调（带即时查询）
    handleClassSelect(item) {
      this.classIdLabel = item.label
      this.classIdValue = item.value

      this.studentId = ''
      this.fetchStudentOptions(this.classIdValue)

      // 如果未选择学生，直接查询班级能力
      if (!this.studentId) {
        this.fetchAndRenderClassData()
      }
    },

    // 查询并渲染班级能力雷达图
    async fetchAndRenderClassData() {
      try {
        const res = await getClassAbility(this.classIdValue)
        if (res.success) {
          this.radarData.class = res.data
          this.renderChart()
        }
      } catch (error) {
        console.error('班级能力加载失败:', error)
      }
    },

    // 查询学生列表
    fetchStudentOptions(classId) {
      const students = this.studentMapping[classId] || []
      this.studentOptions = students.map(id => ({
        label: `学号 ${id}`,
        value: id
      }))
    },

    // 学生选择回调
    handleStudentSelect(item) {
      this.studentId = item.value
    },

    // 查询数据
    async fetchData() {
      if (!this.majorIdValue) {
        this.$message.warning('请先选择专业')
        return
      }

      this.loading = true
      try {
        let studentRes = null
        let classRes = null
        let majorRes = null

        if (this.studentId) {
          [studentRes, classRes, majorRes] = await Promise.all([
            getStudentAbility(this.studentId),
            getClassAbility(this.classIdValue),
            getMajorAbility(this.majorIdValue)
          ])
        } else if (this.classIdValue) {
          [classRes, majorRes] = await Promise.all([
            getClassAbility(this.classIdValue),
            getMajorAbility(this.majorIdValue)
          ])
        } else {
          majorRes = await getMajorAbility(this.majorIdValue)
        }
        // 修改 fetchData 方法中的 radarData 设置部分
        this.radarData = {
          student: studentRes?.success && studentRes.data.studentId !== 'ALL' ? studentRes.data : null,
          class: classRes?.success ? classRes.data : null,
          major: majorRes?.success ? majorRes.data : (
            studentRes?.data?.studentId === 'ALL' ? studentRes.data : null
          )
        }

        this.renderChart()
      } catch (error) {
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },

    // 渲染雷达图
    renderChart() {
      const chartDom = this.$refs.radarChart
      if (!chartDom) return

      const chart = echarts.init(chartDom)
      const series = []

      const buildRadarSeries = (data, name, color) => ({
        name,
        type: 'radar',
        lineStyle: { color },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: `${color}80` },
              { offset: 1, color: `${color}20` }
            ]
          }
        },
        data: [{
          value: [
            data.professionalAbility ?? 0,
            data.generalAbility ?? 0,
            data.practicalAbility ?? 0,
            data.innovationAbility ?? 0,
            data.quality ?? 0
          ]
        }]
      })

      if (this.radarData.major) {
        series.push(buildRadarSeries(this.radarData.major, '专业平均', '#409EFF'))
      }
      if (this.radarData.class) {
        series.push(buildRadarSeries(this.radarData.class, '班级平均', '#F56C6C'))
      }
      if (this.radarData.student) {
        series.push(buildRadarSeries(this.radarData.student, '学生能力', '#67C23A'))
      }

      const option = {
        tooltip: { trigger: 'item' },
        title: { text: '学生能力雷达图对比分析', left: 'center' },
        legend: { data: series.map(s => s.name), top: '10%' },
        radar: {
          indicator: [
            { name: '专业能力', max: 100 },
            { name: '通识能力', max: 100 },
            { name: '实践能力', max: 100 },
            { name: '创新能力', max: 100 },
            { name: '素质', max: 100 }
          ],
          splitLine: { lineStyle: { color: '#ccc', width: 1, type: 'dashed' }},
          axisLine: { lineStyle: { color: '#999' }}
        },
        series
      }

      chart.setOption(option, true)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.selector-container {
  margin-bottom: 30px;
  display: flex;
  gap: 20px;
}

.radar-chart-container,
.el-row,
.el-col {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart {
  width: 600px;
  height: 500px;
  margin: 0 auto;
}

.loading-container {
  padding: 20px;
}
</style>

